package com.zhihuitong.meeting.meeting.create;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.lzy.okgo.model.HttpHeaders;
import com.zhihuitong.meeting.base.BasePresenter;
import com.zhihuitong.meeting.dao.LocalMeetingBean;
import com.zhihuitong.meeting.global.HuaWeiUserProvider;
import com.zhihuitong.meeting.global.MyApplication;
import com.zhihuitong.meeting.login.HuaWeiAuthInfo;
import com.zhihuitong.meeting.net.HttpUtil;
import com.zhihuitong.meeting.net.ServiceAPI;
import com.zhihuitong.meeting.net.callback.MyCallBack;
import com.zhihuitong.meeting.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;

/**
 * 作者： guoyuan
 * 时间 2020/2/24.
 * 文件描述：
 * 版本号：V 1.0
 **/
public class CreatMeetingPresenter extends BasePresenter<CreatMeetingConract.ICreatMeetingView> implements CreatMeetingConract.ICreatMeetingPresenter {

    private String startTime;
    private Integer length;
    private String subject;
    private String mediaTypes;
    private String endTime;

    public CreatMeetingPresenter(CreatMeetingConract.ICreatMeetingView view) {
        super(view);
    }


    /**
     * 预约创建会议
     *
     * @param startTime  ：会议开始时间格式                        yyyy-MM-dd HH:mm
     * @param length     ：会议持续时长，单位分钟，最大值为1440，最短15。default: 30
     * @param subject    ：会议主题。长度限制为128个字符。
     * @param mediaTypes ：会议的媒体类型。。长度限制为128个字符。          由1个或多个枚举String组成，多个枚举时，每个枚举值之间通过“，”逗号分隔，枚举值如下：
     *                   <p>
     *                   "Voice”：语音。
     *                   "Video”：标清视频。
     *                   "HDVideo”：高清视频（与Video互斥，如果同时选择Video、HDVideo，则系统默认选择Video）。
     *                   "Telepresence”：智真(与HDVideo、Video互斥，如果同时选择，系统使用Telepresence)。（预留字段）
     *                   "Data”：多媒体（AS根据系统配置决定是否自动添加Data）。
     * @param endTime    会议结束时间。
     */
    @Override
    public void creatMeeting(@Nullable final String startTime,
                             @Nullable final Integer length,
                             @Nullable final String subject
            , @NonNull final String mediaTypes,
                             @Nullable final String endTime) {
        this.startTime = startTime;
        this.length = length;
        this.subject = subject;
        this.mediaTypes = mediaTypes;
        this.endTime = endTime;

        //获取华为云账号
        getHuaWeiUser();

    }

    /**
     * 正式创建会议
     *
     * @param accessToken
     * @param user
     */
    private void createMeet(String accessToken, final HuaWeiAuthInfo.UserBean user) {
        HttpHeaders headers = new HttpHeaders();
        headers.put("X-Auth-Token", accessToken);
        HashMap<String, Object> map = new HashMap<>();
        map.put("startTime", startTime);
        map.put("length", length);
        map.put("subject", subject);
        map.put("mediaTypes", mediaTypes);
        map.put("isAutoRecord", 0);//自动录播,否
        map.put("recordType", 0);//录播类型 禁用
        map.put("encryptMode", 2);//媒体加密方式,不加密
        HttpUtil.<List<MeetingInfo>>post(ServiceAPI.HUAWEI_CONFERENCES, map, ServiceAPI.HUAWEI_CONFERENCES)
                .headers(headers)
                .execute(new MyCallBack<List<MeetingInfo>>() {
                    @Override
                    public void success(List<MeetingInfo> body) {
                        //释放账号
                        releaseHuaWeiUser();

                        if (body != null && body.size() > 0) {
                            MeetingInfo meetingInfo = body.get(0);
                            getView().createMeetingSuc(meetingInfo);
                            //保存会议信息至本地数据库
                            LocalMeetingBean localMeetingBean = new LocalMeetingBean();
                            //当前用户id
                            localMeetingBean.setUserId(user.userId);
                            //会议预订者id
                            localMeetingBean.setCreateUserId(meetingInfo.userUUID);
                            //会议主题
                            localMeetingBean.setSubject(subject);
                            //会议接入码
                            localMeetingBean.setAccessNumber(meetingInfo.accessNumber);
                            //主持人密码
                            localMeetingBean.setChairPwd(meetingInfo.passwordEntry.get(0).password);
                            //来宾密码
                            localMeetingBean.setGeneralPwd(meetingInfo.passwordEntry.get(1).password);
                            //预订者昵称
                            localMeetingBean.setScheduserName(MyApplication.getLocalUserName());
                            //会议id
                            localMeetingBean.setConferenceID(meetingInfo.conferenceID);
                            //   //“Schedule”：预定状态。
                            //    //“Creating”：正在创建状态。
                            //    //“Created”：会议已经被创建，并正在召开。
                            //    //“Destroyed”：会议已经关闭
                            localMeetingBean.setConferenceState(meetingInfo.conferenceState);
                            //生成时间
                            localMeetingBean.setCreateTime(System.currentTimeMillis());
                            //预估时长
                            localMeetingBean.setLength(length);
                            //开始时间
                            localMeetingBean.setStartTime(startTime);
                            //结束时间
                            localMeetingBean.setEndTime(endTime);
                            //会议类型
                            localMeetingBean.setMediaTypes(mediaTypes);
                            boolean save = localMeetingBean.save();
                            if (!save) {
                                ToastUtils.showToast("会议保存失败!");
                            } else {
                                EventBus.getDefault().post(localMeetingBean);
                            }
                        }
                    }

                    @Override
                    public void error(String msg) {
                        getView().createMeetingFail(msg);
                        //释放账号
                        releaseHuaWeiUser();
                    }
                });
    }


    /**
     * 获取华为云账号
     */
    private void getHuaWeiUser() {
        HuaWeiUserProvider.getUser(MyApplication.getLocalAccount(), MyApplication.getLocalPwd(), new HuaWeiUserProvider.onHuaWeiUserListener() {
            @Override
            public void onHuaWeiUserSuccess(String userId, String pwd) {
                //获取到账号.登录鉴权
                huaweiAuth(userId, pwd);
            }

            @Override
            public void onHuaWeiUserFail(String msg) {
                getView().createMeetingFail(msg);
            }
        });
    }

    /**
     * 登录华为云账号鉴权
     *
     * @param account
     * @param pwd
     */
    private void huaweiAuth(final String account, final String pwd) {
        HuaWeiUserProvider.huaweiAuth(account, pwd, new HuaWeiUserProvider.onHuaWeiUserAuthListener() {
            @Override
            public void onHuaWeiUserAuthSuccess(String accessToken, HuaWeiAuthInfo.UserBean user) {
                //鉴权成功,创建会议
                createMeet(accessToken, user);
            }

            @Override
            public void onHuaWeiUserAuthFail(String msg) {
                getView().createMeetingFail(msg);
            }
        });
    }

    /**
     * 释放华为云账号
     */
    private void releaseHuaWeiUser() {
        HuaWeiUserProvider.releaseHuaWeiUser(MyApplication.getLocalAccount(), MyApplication.getLocalPwd(), new HuaWeiUserProvider.onHuaWeiUserListener() {
            @Override
            public void onHuaWeiUserSuccess(String userId, String pwd) {
                ToastUtils.showToast("华为账号释放成功!");
            }

            @Override
            public void onHuaWeiUserFail(String msg) {
                ToastUtils.showToast("华为云账号释放失败,请请至主页手动释放!!!\n错误信息: " + msg);
            }
        });
    }

}
